/**
 * TodoList 前端 JavaScript 应用
 * 负责与后端API交互，处理用户界面逻辑
 */

class TodoApp {
    constructor() {
        // 状态管理
        this.todos = [];
        this.todosByDate = {
            today_pending: [],
            today_completed: [],
            yesterday_tasks: []
        };
        this.currentEditId = null;
        this.currentDeleteId = null;
        this.appConfig = null;
        
        // DOM元素引用
        this.elements = {
            // 输入和按钮
            newTodoInput: document.getElementById('new-todo-input'),
            addTodoBtn: document.getElementById('add-todo-btn'),
            
            // 列表容器
            pendingTodos: document.getElementById('pending-todos'),
            completedTodos: document.getElementById('completed-todos'),
            yesterdayTodos: document.getElementById('yesterday-todos'),
            emptyState: document.getElementById('empty-state'),
            
            // 统计信息
            totalCount: document.getElementById('total-count'),
            completedCount: document.getElementById('completed-count'),
            pendingCount: document.getElementById('pending-count'),
            completedPercent: document.getElementById('completed-percent'),
            
            // 编辑模态框
            editModal: document.getElementById('edit-modal'),
            editTodoInput: document.getElementById('edit-todo-input'),
            saveEditBtn: document.getElementById('save-edit-btn'),
            cancelEditBtn: document.getElementById('cancel-edit-btn'),
            modalClose: document.getElementById('modal-close'),
            
            // 删除确认模态框
            deleteModal: document.getElementById('delete-modal'),
            deletePreview: document.getElementById('delete-preview'),
            confirmDeleteBtn: document.getElementById('confirm-delete-btn'),
            cancelDeleteBtn: document.getElementById('cancel-delete-btn'),
            deleteModalClose: document.getElementById('delete-modal-close'),
            
            // 通知和加载
            notification: document.getElementById('notification'),
            loading: document.getElementById('loading'),

            // 版本信息
            versionText: document.querySelector('.version-text'),
            authorText: document.querySelector('.author-text')
        };
        
        // 初始化应用
        this.init();
    }
    
    /**
     * 初始化应用
     */
    async init() {
        console.log('TodoApp 初始化开始...');
        
        try {
            // 获取应用配置
            await this.loadAppConfig();
            // 绑定事件监听器
            this.bindEvents();
            
            // 加载待办事项数据
            await this.loadTodos();
            
            // 聚焦到输入框
            this.elements.newTodoInput.focus();
            
            console.log('TodoApp 初始化完成');
        } catch (error) {
            console.error('初始化失败:', error);
            this.showNotification('应用初始化失败', 'error');
        }
    }

    /**
     * 加载应用配置
     */
    async loadAppConfig() {
        try {
            console.log('正在加载应用配置...')
            this.appConfig = await pywebview.api.get_app_config();
            console.log('应用配置:', this.appConfig);

            // 更新版本信息
            this.updateVersionInfo();
        } catch (error) {
            console.error('加载应用配置失败:', error);
            // 使用默认配置
            this.appConfig = {
                version: '1.0.0',
                author: 'super'
            };
            this.updateVersionInfo();
        }
    }

    /**
     * 更新版本信息
     */
    updateVersionInfo() {
        if (this.elements.versionText && this.appConfig) {
            this.elements.versionText.textContent = `${this.appConfig.version}`;
        }
        if (this.elements.authorText && this.appConfig) {
            this.elements.authorText.textContent = `${this.appConfig.author}`;
        }
    }

    /**
     * 绑定所有事件监听器
     */
    bindEvents() {
        // 添加任务事件
        this.elements.addTodoBtn.addEventListener('click', () => this.addTodo());
        this.elements.newTodoInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addTodo();
            }
        });
        
        // 编辑模态框事件
        this.elements.saveEditBtn.addEventListener('click', () => this.saveEdit());
        this.elements.cancelEditBtn.addEventListener('click', () => this.closeEditModal());
        this.elements.modalClose.addEventListener('click', () => this.closeEditModal());
        this.elements.editTodoInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.saveEdit();
            } else if (e.key === 'Escape') {
                this.closeEditModal();
            }
        });
        
        // 删除确认模态框事件
        this.elements.confirmDeleteBtn.addEventListener('click', () => this.confirmDelete());
        this.elements.cancelDeleteBtn.addEventListener('click', () => this.closeDeleteModal());
        this.elements.deleteModalClose.addEventListener('click', () => this.closeDeleteModal());
        
        // 模态框背景点击关闭
        this.elements.editModal.addEventListener('click', (e) => {
            if (e.target === this.elements.editModal) {
                this.closeEditModal();
            }
        });
        
        this.elements.deleteModal.addEventListener('click', (e) => {
            if (e.target === this.elements.deleteModal) {
                this.closeDeleteModal();
            }
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            // ESC 关闭模态框
            if (e.key === 'Escape') {
                this.closeEditModal();
                this.closeDeleteModal();
            }
        });
        
        console.log('事件监听器绑定完成');
    }
    
    /**
     * 从后端加载按日期分组的待办事项
     */
    async loadTodos() {
        this.showLoading(true);
        
        try {
            console.log('正在加载待办事项...');
            
            // 调用后端API获取按日期分组的待办事项
            const todosByDate = await pywebview.api.get_todos_by_date();
            console.log('加载到的按日期分组待办事项:', todosByDate);
            
            this.todosByDate = todosByDate || {
                today_pending: [],
                today_completed: [],
                yesterday_tasks: []
            };
            
            // 为了兼容性，也保留所有任务的列表
            this.todos = [
                ...this.todosByDate.today_pending,
                ...this.todosByDate.today_completed,
                ...this.todosByDate.yesterday_tasks
            ];
            
            this.renderTodos();
            this.updateStats();
            
            console.log(`成功加载任务: 今日待完成 ${this.todosByDate.today_pending.length}, 今日已完成 ${this.todosByDate.today_completed.length}, 昨日 ${this.todosByDate.yesterday_tasks.length}`);
            
        } catch (error) {
            console.error('加载待办事项失败:', error);
            this.showNotification('加载数据失败，请刷新页面重试', 'error');
            this.todosByDate = {
                today_pending: [],
                today_completed: [],
                yesterday_tasks: []
            };
            this.todos = [];
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 添加新的待办事项
     */
    async addTodo() {
        const content = this.elements.newTodoInput.value.trim();
        
        if (!content) {
            this.showNotification('请输入待办事项内容', 'warning');
            this.elements.newTodoInput.focus();
            return;
        }
        
        if (content.length > 200) {
            this.showNotification('待办事项内容不能超过200个字符', 'warning');
            return;
        }
        
        this.showLoading(true);
        
        try {
            console.log('正在添加待办事项:', content);
            
            // 调用后端API添加待办事项
            const result = await pywebview.api.add_todo(content);
            
            if (result.error) {
                throw new Error(result.error);
            }
            
            console.log('添加成功:', result);
            
            // 清空输入框
            this.elements.newTodoInput.value = '';
            
            // 重新加载数据
            await this.loadTodos();
            
            this.showNotification('任务添加成功！');
            
            // 聚焦到输入框
            this.elements.newTodoInput.focus();
            
        } catch (error) {
            console.error('添加待办事项失败:', error);
            this.showNotification('添加任务失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 删除待办事项
     */
    async deleteTodo(todoId) {
        const todo = this.todos.find(t => t.id === todoId);
        if (!todo) return;
        
        // 显示删除确认模态框
        this.currentDeleteId = todoId;
        this.elements.deletePreview.textContent = `"${todo.content}"`;
        this.elements.deleteModal.style.display = 'flex';
    }
    
    /**
     * 确认删除操作
     */
    async confirmDelete() {
        if (!this.currentDeleteId) return;
        
        this.showLoading(true);
        
        try {
            console.log('正在删除待办事项:', this.currentDeleteId);
            
            // 调用后端API删除待办事项
            const success = await pywebview.api.delete_todo(this.currentDeleteId);
            
            if (!success) {
                throw new Error('删除操作失败');
            }
            
            console.log('删除成功');
            
            // 关闭模态框
            this.closeDeleteModal();
            
            // 重新加载数据
            await this.loadTodos();
            
            this.showNotification('任务删除成功！');
            
        } catch (error) {
            console.error('删除待办事项失败:', error);
            this.showNotification('删除任务失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 编辑待办事项
     */
    editTodo(todoId) {
        const todo = this.todos.find(t => t.id === todoId);
        if (!todo) return;
        
        // 显示编辑模态框
        this.currentEditId = todoId;
        this.elements.editTodoInput.value = todo.content;
        this.elements.editModal.style.display = 'flex';
        
        // 聚焦并选中文本
        setTimeout(() => {
            this.elements.editTodoInput.focus();
            this.elements.editTodoInput.select();
        }, 100);
    }
    
    /**
     * 保存编辑
     */
    async saveEdit() {
        if (!this.currentEditId) return;
        
        const newContent = this.elements.editTodoInput.value.trim();
        
        if (!newContent) {
            this.showNotification('请输入待办事项内容', 'warning');
            this.elements.editTodoInput.focus();
            return;
        }
        
        if (newContent.length > 200) {
            this.showNotification('待办事项内容不能超过200个字符', 'warning');
            return;
        }
        
        this.showLoading(true);
        
        try {
            console.log('正在更新待办事项:', this.currentEditId, newContent);
            
            // 调用后端API更新待办事项
            const result = await pywebview.api.update_todo(this.currentEditId, newContent);
            
            if (result && result.error) {
                throw new Error(result.error);
            }
            
            if (!result) {
                throw new Error('更新操作失败');
            }
            
            console.log('更新成功');
            
            // 关闭模态框
            this.closeEditModal();
            
            // 重新加载数据
            await this.loadTodos();
            
            this.showNotification('任务更新成功！');
            
        } catch (error) {
            console.error('更新待办事项失败:', error);
            this.showNotification('更新任务失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 切换完成状态
     */
    async toggleComplete(todoId) {
        this.showLoading(true);
        
        try {
            console.log('正在切换完成状态:', todoId);
            
            // 调用后端API切换完成状态
            const success = await pywebview.api.toggle_complete(todoId);
            
            if (!success) {
                throw new Error('状态切换失败');
            }
            
            console.log('状态切换成功');
            
            // 重新加载数据
            await this.loadTodos();
            
        } catch (error) {
            console.error('切换完成状态失败:', error);
            this.showNotification('状态切换失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 渲染待办事项列表
     */
    renderTodos() {
        // 渲染今日待完成任务
        this.elements.pendingTodos.innerHTML = '';
        this.todosByDate.today_pending.forEach(todo => {
            const todoElement = this.createTodoElement(todo);
            this.elements.pendingTodos.appendChild(todoElement);
        });
        
        // 渲染今日已完成任务
        this.elements.completedTodos.innerHTML = '';
        this.todosByDate.today_completed.forEach(todo => {
            const todoElement = this.createTodoElement(todo);
            this.elements.completedTodos.appendChild(todoElement);
        });
        
        // 渲染昨日任务
        this.elements.yesterdayTodos.innerHTML = '';
        this.todosByDate.yesterday_tasks.forEach(todo => {
            const todoElement = this.createTodoElement(todo, true); // 昨日任务只读
            this.elements.yesterdayTodos.appendChild(todoElement);
        });
        
        // 显示或隐藏空状态
        const totalTasks = this.todosByDate.today_pending.length + 
                          this.todosByDate.today_completed.length + 
                          this.todosByDate.yesterday_tasks.length;
        
        if (totalTasks === 0) {
            this.elements.emptyState.style.display = 'block';
        } else {
            this.elements.emptyState.style.display = 'none';
        }
        
        console.log(`渲染完成: 今日待完成 ${this.todosByDate.today_pending.length}, 今日已完成 ${this.todosByDate.today_completed.length}, 昨日 ${this.todosByDate.yesterday_tasks.length}`);
    }
    
    /**
     * 创建单个待办事项DOM元素
     */
    createTodoElement(todo, readonly = false) {
        const todoDiv = document.createElement('div');
        todoDiv.className = `todo-item ${todo.completed ? 'completed' : ''}`;
        todoDiv.setAttribute('data-id', todo.id);
        
        // 创建复选框
        const checkbox = document.createElement('div');
        checkbox.className = `todo-checkbox ${todo.completed ? 'checked' : ''}`;
        checkbox.addEventListener('click', () => this.toggleComplete(todo.id));
        
        // 创建内容区域
        const content = document.createElement('div');
        content.className = 'todo-content';
        content.textContent = todo.content;
        content.title = todo.content; // 鼠标悬停时显示完整内容
        
        // 创建操作按钮容器
        const actions = document.createElement('div');
        actions.className = 'todo-actions';
        
        // 如果不是只读模式，添加编辑和删除按钮
        if (!readonly) {
            // 编辑按钮
            const editBtn = document.createElement('button');
            editBtn.className = 'action-btn edit-btn';
            editBtn.innerHTML = '✏️';
            editBtn.title = '编辑';
            editBtn.addEventListener('click', () => this.editTodo(todo.id));
            
            // 删除按钮
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'action-btn delete-btn';
            deleteBtn.innerHTML = '🗑️';
            deleteBtn.title = '删除';
            deleteBtn.addEventListener('click', () => this.deleteTodo(todo.id));
            
            // 组装元素
            actions.appendChild(editBtn);
            actions.appendChild(deleteBtn);
        } else {
            // 只读模式显示日期标签
            const dateLabel = document.createElement('span');
            dateLabel.className = 'date-label';
            const createdDate = new Date(todo.created_at);
            dateLabel.textContent = createdDate.toLocaleDateString('zh-CN', { 
                month: 'short', 
                day: 'numeric' 
            });
            actions.appendChild(dateLabel);
        }
        
        todoDiv.appendChild(checkbox);
        todoDiv.appendChild(content);
        todoDiv.appendChild(actions);
        
        return todoDiv;
    }
    
    /**
     * 更新统计信息
     */
    async updateStats() {
        try {
            // 调用后端API获取今日任务统计信息
            const stats = await pywebview.api.get_today_stats();
            
            this.elements.totalCount.textContent = stats.total || 0;
            this.elements.completedCount.textContent = stats.completed || 0;
            this.elements.pendingCount.textContent = stats.pending || 0;
            const completionRateElement = document.getElementById('completion_rate-count')
            if(completionRateElement) {
                completionRateElement.textContent = (stats.completion_rate || 0) + '%';
            }
            
            console.log('统计信息更新:', stats);
            
        } catch (error) {
            console.error('获取统计信息失败:', error);
            // 使用本地计算的统计信息作为备选
            const total = this.todosByDate.today_pending.length + this.todosByDate.today_completed.length;
            const completed = this.todosByDate.today_completed.length;
            const pending = this.todosByDate.today_pending.length;
            const completionRate = total > 0 ? Math.round((completed / total) * 1000) / 10 : 0;
            
            this.elements.totalCount.textContent = total;
            this.elements.completedCount.textContent = completed;
            this.elements.pendingCount.textContent = pending;
            const completionRateElement = document.getElementById('completion_rate-count')
            if(completionRateElement) {
                completionRateElement.textContent = (completionRate + '%');
            }
        }
    }
    
    /**
     * 关闭编辑模态框
     */
    closeEditModal() {
        this.elements.editModal.style.display = 'none';
        this.currentEditId = null;
        this.elements.editTodoInput.value = '';
    }
    
    /**
     * 关闭删除确认模态框
     */
    closeDeleteModal() {
        this.elements.deleteModal.style.display = 'none';
        this.currentDeleteId = null;
        this.elements.deletePreview.textContent = '';
    }
    
    /**
     * 显示通知消息
     */
    showNotification(message, type = 'success') {
        const notification = this.elements.notification;
        const textElement = notification.querySelector('.notification-text');
        
        // 清除之前的类型类
        notification.className = 'notification';
        if (type !== 'success') {
            notification.classList.add(type);
        }
        
        textElement.textContent = message;
        notification.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
        
        console.log(`通知 (${type}):`, message);
    }
    
    /**
     * 显示或隐藏加载提示
     */
    showLoading(show) {
        this.elements.loading.style.display = show ? 'flex' : 'none';
        
        // 禁用/启用界面交互
        const interactiveElements = [
            this.elements.newTodoInput,
            this.elements.addTodoBtn
        ];
        
        interactiveElements.forEach(element => {
            element.disabled = show;
        });
    }
}

/**
 * 等待pywebview API准备就绪，然后初始化应用
 */
function initApp() {
    // 检查pywebview API是否可用
    if (typeof pywebview !== 'undefined' && pywebview.api) {
        console.log('PyWebview API 已准备就绪，启动应用...');
        window.todoApp = new TodoApp();
    } else {
        console.log('等待 PyWebview API 准备就绪...');
        // 如果API还没准备好，等待一段时间后重试
        setTimeout(initApp, 100);
    }
}

/**
 * 页面加载完成后初始化应用
 */
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，准备初始化应用...');
    initApp();
});

/**
 * 错误处理 - 捕获未处理的JavaScript错误
 */
window.addEventListener('error', function(event) {
    console.error('JavaScript 错误:', event.error);
    
    // 如果应用已初始化，显示错误通知
    if (window.todoApp) {
        window.todoApp.showNotification('发生了一个错误，请刷新页面重试', 'error');
    }
});

/**
 * Promise 错误处理
 */
window.addEventListener('unhandledrejection', function(event) {
    console.error('未处理的 Promise 错误:', event.reason);
    
    // 如果应用已初始化，显示错误通知
    if (window.todoApp) {
        window.todoApp.showNotification('操作失败，请重试', 'error');
    }
});

